package heap;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 *  https://leetcode.com/problems/kth-largest-element-in-an-array/
 *
 * 获取第K大的元素
 */
public class Kth {

    public static void main(String[] args) {

        int[] nums = {3,2,1,5,6,4};
        System.out.println(new Kth().findKthLargestHeap(nums,5));
        System.out.println(new Kth().findKthLargest(nums,5));

    }

    //非最优，中间可能并非完全排好序
    public int findKthLargestHeap(int[] nums, int k) {
        PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(k, new Comparator<Integer>() {
            public int compare(Integer num1, Integer num2) {
                return num2 - num1;
            }
        });

        for (int i : nums) {
            maxHeap.add(i);
        }

        // 6 5 4 2 3 1
        System.out.println(maxHeap.toString());

        for (int i = 0; i < k - 1; i++) {
            maxHeap.poll();
        }
        return maxHeap.poll();
    }

    public int findKthLargest(int[] nums, int k) {
        if (nums == null || nums.length == 0 || k < 1 || k > nums.length) {
            return -1;
        }
        return partition(nums, 0, nums.length - 1, nums.length - k);
    }

    /**
     * 快速排序
     * @param nums 集合
     * @param start 开始
     * @param end 截止
     * @param k k
     * @return 结果
     */
    public int partition(int[] nums, int start, int end, int k) {
        if (start >= end) {
            return nums[k];
        }

        int left = start;
        int right = end;
        int pivot = nums[(start + end) / 2];
        while (left <= right) {
            while(left <= right && nums[left] < pivot) {
                left++;
            }
            while (left <= right && nums[right] > pivot) {
                right--;
            }
            if (left <= right) {
                int temp = nums[left];
                nums[left] = nums[right];
                nums[right] = temp;
                left++;
                right--;
            }
        }
        if (k <= right) {
            return partition(nums, start, right, k);
        }
        if (k >= left) {
            return partition(nums, left, end, k);
        }

        return nums[k];
    }

}
